﻿using System;
using System.Collections.Generic;
using CoreVirtuoso.Descriptions;
using Infrastructure.Lgd.Interfaces;
using NGenerics.DataStructures;

namespace Infrastructure.Lgd
{
   public class LgdTreeFilter : ILgdTreeFilter
   {
      public GeneralTree<EntityDescription> FilterCategoriesTree(GeneralTree<string> categoriesRootNode, List<string> categoriesToFilter)
      {
         var filteredCategoriesRootNode = new GeneralTree<EntityDescription>(null);

         foreach (var categoryNode in categoriesRootNode.ChildNodes)
         {
            var filteredCategoryNode = FilterCategoriesTreeInternal(categoryNode, categoriesToFilter);
            if (filteredCategoryNode != null)
               filteredCategoriesRootNode.Add(filteredCategoryNode);
         }

         return filteredCategoriesRootNode;
      }

      //ToDo: Converting from string to EntityDescription should go not here but in LgdTreeBuilder
      private GeneralTree<EntityDescription> FilterCategoriesTreeInternal(GeneralTree<string> parentCategoryNode, List<string> categoriesToFilter)
      {
         bool isNodeCreated = false;

         GeneralTree<EntityDescription> categoryNode = null;

         if (categoriesToFilter.Contains(parentCategoryNode.Data))
         {
            isNodeCreated = true;
            categoryNode = GetCategoryNode(parentCategoryNode.Data);
         }

         foreach (var childCategoryNode in parentCategoryNode.ChildNodes)
         {
            var childNode = FilterCategoriesTreeInternal(childCategoryNode, categoriesToFilter);
            if (childNode != null)
            {
               if (!isNodeCreated)
               {
                  isNodeCreated = true;
                  categoryNode = GetCategoryNode(parentCategoryNode.Data);
               }

               categoryNode.Add(childNode);
            }
         }

         return categoryNode;
      }

      //ToDo: Move it out and call from LgdTreeBuilder as dependency
      private GeneralTree<EntityDescription> GetCategoryNode(string categoryUri)
      {
         EntityDescription entityDescription = new EntityDescription(categoryUri,
                                                                     categoryUri.Split(new[] { "ontology/" }, StringSplitOptions.None)[1]);
         GeneralTree<EntityDescription> categoryNode = new GeneralTree<EntityDescription>(entityDescription);

         return categoryNode;
      }
   }
}
